package com.wujilee.wujileenetty.netty.netty.decoder.message;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;

import java.util.List;

/**
 * @author liwuji
 * @date 2024/8/27
 * @desc
 **/
public class MsgPackServer {
    public static void main(String[] args) throws InterruptedException {

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();

        NioEventLoopGroup workerGroup = new NioEventLoopGroup(10);

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4) );
                        ch.pipeline().addLast("msgpack decoder", new MsgPackDecoder());
                        // 该类在消息前增加4个字节记录消息长度
                        ch.pipeline().addLast(new LengthFieldPrepender(4));
                        ch.pipeline().addLast("msgpack encoder", new MsgpackEncode());
                        ch.pipeline().addLast("hello",new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                System.out.println("连接建立成功");
                            }

                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                System.out.println("接收到来自客户端的消息,"+ msg);

                             }
                        });
                    }
                });

        // 绑定接口 同步
        ChannelFuture sync = serverBootstrap.bind(8080).sync();
        ChannelFuture sync1 = sync.channel().closeFuture().sync();
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
